package bid.web;

import bid.dao.UserDao;
import bid.dao.impl.UserDaoImpl;
import bid.dao.UserRoleDao;
import bid.dao.impl.UserRoleDaoImpl;
import bid.entity.User;
import bid.entity.UserRole;
import bid.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * @author oldliu
 * @since 1.0
 */
//完成用户功能的通用servlet
@WebServlet(value = "*.user")
public class User2Servlet extends HttpServlet {

    UserDao userDao = new UserDaoImpl();
    UserRoleDao roleDao = new UserRoleDaoImpl();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);//保持一致
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=UTF-8");
        String path = req.getServletPath();
        System.out.println("请求地址：" + path);//    /add.proj
        path = path.substring(1, path.length() - 5);
        System.out.println("这就是操作：" + path);
        if ("add".equals(path)) {
            add(req, resp);
        } else if ("update".equals(path)) {
            update(req, resp);
        } else if ("del".equals(path)) {
            del(req, resp);
        } else if ("search".equals(path)) {
            search(req, resp);
        } else if ("reset".equals(path)) {
            reset(req, resp);
        } else if ("toAdd".equals(path)) {
            toAdd(req, resp);
        } else if ("toUpdate".equals(path)) {
            toUpdate(req, resp);
        } else if ("login".equals(path)) {
            login(req, resp);
        } else {
            resp.getWriter().println("这是未知操作");
        }
    }

    //重置密码
    public void reset(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    public void search(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        String name = StringUtils.trim(request.getParameter("name"));
        String username = StringUtils.trim(request.getParameter("username"));
        Date start = StringUtils.toDate(request.getParameter("start"));
        Date end = StringUtils.toDate(request.getParameter("end"));
        int pageNo = StringUtils.toInt(request.getParameter("pageNo"), 1);
        int pageSize = 10;
        List<User> users = userDao.search(pageNo, pageSize, name, username, start, end);

        long total = userDao.searchTotal(name, username, start, end);

        long pageNums = total / pageSize + (total % pageSize == 0 ? 0 : 1);//求页数

        request.setAttribute("users", users);
        request.setAttribute("pageNums", pageNums);
        request.setAttribute("pageNo", pageNo);
        request.setAttribute("name", name);
        request.setAttribute("username", username);
        request.setAttribute("start", start);
        request.setAttribute("end", end);
        //转发
        request.getRequestDispatcher("/WEB-INF/view/user/users.jsp").forward(request, resp);

    }

    public void del(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {

        long id = Long.parseLong(request.getParameter("id"));
        UserDao userDao = new UserDaoImpl();
        int r = userDao.del(id);
        if (r > 0) {
            resp.sendRedirect("search.user");///!!!!!!!!11
            return;
        }
        resp.getWriter().print("<script>alert('删除失败');window.history.back();</script>");
    }

    //跳转到新增的jsp
    public void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        List<UserRole> roles = roleDao.findAll();
        req.setAttribute("roles", roles);
        req.getRequestDispatcher("/WEB-INF/view/user/addUser.jsp").forward(req, resp);
    }

    //跳转到修改的jsp
    public void toUpdate(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        long id = Long.parseLong(req.getParameter("id"));
        User user = userDao.get(id);
        req.setAttribute("user", user);

        List<UserRole> roles = roleDao.findAll();
        req.setAttribute("roles", roles);

        req.getRequestDispatcher("/WEB-INF/view/user/updateUser.jsp").forward(req, resp);

    }

    public void update(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        user.setId(Long.parseLong(request.getParameter("id")));
        user.setName(request.getParameter("name"));
        user.setPassword(request.getParameter("password"));
        user.setUsername(request.getParameter("username"));
        user.setUnit(request.getParameter("unit"));
        user.setIdcard(request.getParameter("idcard"));
        user.setRoleid(Long.parseLong(request.getParameter("role")));
        user.setTelephone(request.getParameter("telephone"));
        user.setEnterdate(StringUtils.toDate(request.getParameter("enterdate")));

        int r = userDao.update(user);
        if (r > 0) {
            resp.getWriter().print("<script>alert('修改成功');window.location='search.user';</script>");
            return;
        }
        resp.getWriter().print("<script>alert('修改失败');window.history.back();</script>");

    }

    public void login(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        String name = request.getParameter("username");
        String pass = request.getParameter("pass");

        User user = userDao.login(name, pass);
        if (user == null) {
            resp.getWriter().print("错误的用户名或者密码！<a href='login.jsp'>返回</a>");
            return;
        }
        HttpSession session = request.getSession();
        session.setAttribute("LOGIN_USER", user);
        resp.sendRedirect("main.jsp");
    }

    public void add(HttpServletRequest request, HttpServletResponse resp) throws ServletException, IOException {
        User user = new User();
        user.setName(request.getParameter("name"));
        user.setPassword(request.getParameter("password"));
        user.setUsername(request.getParameter("username"));
        user.setUnit(request.getParameter("unit"));
        user.setIdcard(request.getParameter("idcard"));
        user.setRoleid(Long.parseLong(request.getParameter("role")));
        user.setTelephone(request.getParameter("telephone"));
        user.setEnterdate(StringUtils.toDate(request.getParameter("enterdate")));

        int r = userDao.add(user);
        if (r > 0) {
            resp.getWriter().print("<script>alert('新增成功');window.location='search.user';</script>");
            return;
        }
        resp.getWriter().print("<script>alert('新增失败');window.history.back();</script>");

    }
}
